# -*- coding: utf8 -*-

import os
import datetime
import logging
import sys

# XML Writer
ONEBOX_BEGIN = """<?xml version="1.0" encoding="UTF-8" ?>
<Results>
  <ResultSpec id="寻亲">
    <Query>[PeopleName]</Query>
    <Response format="image">
      <Output name="image_src">http://eq-cse.googlecode.com/files/notepad.gif</Output>
      <Output name="image_size">mini_square</Output>
      <Output name="title">[0.name]</Output>
      <Output name="text1">[0.text1]</Output>
      <Output name="text2">[0.text2]</Output>
      <Output name="text3">(信息按原样提供，仅供参考，Google未作任何核实)</Output>
    </Response>
  </ResultSpec>
"""

ONEBOX_PERSON_BEGIN = """
  <DataObject id="%s" type="PeopleName">
    <QueryName value="%s" />
    <Attribute name="name" value="%s" />
"""

ONEBOX_PERSON_END = """
  </DataObject>
"""

ONEBOX_END = """
</Results>
"""

def XMLWriter(outfname, persons):
  basefname = os.path.basename(outfname)
  out = file(outfname, 'wb')
  out.write(ONEBOX_BEGIN)

  for id, person in zip(xrange(len(persons)), persons):
    key = "%s_ID_%07d" % (basefname, id)
    out.write(ONEBOX_PERSON_BEGIN % (key, person.name, person.name))
    out.write('''    <Attribute name="text1" value="''')
    if person.sex:
      out.write(person.sex + " - ")
    if person.age:
      out.write(person.age)
      if person.age.isdigit():
        out.write("岁")
      out.write(" - ")
    out.write("电话: ")
    if person.contact:
      out.write(person.contact)
    else:
      out.write("不详")
    if person.address:
      out.write(" - " + person.address)
    if person.unit:
      out.write(" - " + person.unit)
    if person.status:
      out.write(" - " + person.status)
    out.write('''" />\n''')
    out.write('''    <Attribute name="text2" value="''')
    out.write("医院: ")
    if person.hospital:
      out.write(person.hospital)
      if person.section:
        out.write(" " + person.section)
    else:
      out.write("不详")
    if person.hospital_contact:
      out.write(" " + person.hospital_contact)
    now = datetime.datetime.now()
    out.write(" %d月%d日%02d时%02d分更新" % (now.month, now.day, now.hour, now.minute))
    out.write('''" />''')
    out.write(ONEBOX_PERSON_END)

  out.write(ONEBOX_END)
  out.close()

# TSV Writer
TSV_BEGIN="""# subscribed links TSV file
type	p	name	text1	text2	src_text	src_link	src_url
"""

def TSVWriter(outfname, persons):
  basefname = os.path.basename(outfname)
  out = file(outfname, 'wb')
  out.write(TSV_BEGIN)

  for id, person in zip(xrange(len(persons)), persons):
    # First section: "data \t PeopleName \t people-Id \t people-Name \t"
    key = "%d" % id
    out.write("data\tp\t%s\t%s\t" % (key, person.name))

    # Second section: "sex - age - contact - address unit - status \t"
    if person.sex:
      out.write(person.sex + " - ")
    if person.age:
      out.write(person.age)
      if person.age.isdigit():
        out.write("岁")
      out.write(" - ")
    out.write("电话: ")
    if person.contact:
      out.write(person.contact)
    else:
      out.write("不详")
    if person.address:
      out.write(" - " + person.address)
    if person.unit:
      out.write(" - " + person.unit)
    if person.status:
      out.write(" - " + person.status)
    out.write("\t")

    # Third section: "hospital - section - hospital contact - update \t"
    out.write("医院: ")
    if person.hospital:
      out.write(person.hospital)
      # Hide for privacy reason.
      # if person.section:
      #  out.write(" - " + person.section)
    else:
      out.write("不详")
    if person.hospital_contact:
      out.write(" - " + person.hospital_contact)
    now = datetime.datetime.now()
    out.write(" - %d月%d日%02d时%02d分更新" % (now.month, now.day, now.hour, now.minute))
    out.write("\t")

    if person.source and not person.source.startswith(r'http://'):
      out.write("来源于: %s" % person.source)
    out.write("\t")

    if person.source and person.source.startswith(r'http://'):
      out.write("来源")
    out.write("\t")

    if person.source and person.source.startswith(r'http://'):
      out.write(person.source)
    out.write("\t")

    # Forth section: "name \n"
    out.write(person.name + "\n")
  out.close()

# GeoMeta Writer
def GeoMetaWriter(outfname, persons):
  basefname = os.path.basename(outfname)
  out = file(outfname, "wb")
  for person in persons:
    out.write("%s\t" % person.name)
    person.address and out.write(person.address)
    person.unit and out.write(person.unit)
    out.write("\n")
  out.close()

def OneboxWriter(outfname, persons):
  TSVWriter(outfname + ".tsv", persons)
  GeoMetaWriter(outfname + ".geo", persons)

SHENGHUO_FIELDS_EN = ("name", "sex", "age", "contact", "address", "unit", "other",
                      "hospital", "section", "status", "hospital_contact", "source")
# Shenghuo Writer
def ShenghuoWriter(outfname, persons):
  basefname = os.path.basename(outfname)
  out = file(outfname + ".shenghuo", "wb")
  out.write("\t".join(SHENGHUO_FIELDS_EN))
  out.write("\n")
  for person in persons:
    out.write("\t".join([person.__dict__[field] or "" for field in SHENGHUO_FIELDS_EN]))
    out.write("\n")
  out.close()
